package tq.com.tqteacher.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;

import com.browser.DetailPicsActivity;
import com.githang.statusbar.StatusBarCompat;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

import tq.com.systools.system.AlertDialogHelper;
import tq.com.tqcom.base.BaseActivity;
import tq.com.tqcom.net.INetCallback;
import tq.com.tqcom.net.TQNetResult;
import tq.com.tqcom.net.TQPictureUpload;
import tq.com.tqcom.util.TQLoadingHelper;
import tq.com.tqcom.util.TQSystemDefine;
import tq.com.tqcom.view.TQHeader5View;
import tq.com.tqteacher.R;
import tq.com.tqteacher.adapt.TQCropSetsAdapt;
import tq.com.tqteacher.model.TQAtachModel;
import tq.com.tqteacher.model.TQNewPingJiangPublish;
import tq.com.tqteacher.model.TQPublishType;
import tq.com.tqteacher.net.TQNetInterface;

public class TQCropPictureActivity extends BaseActivity {
    private TQHeader5View mHeader5View;

    private RecyclerView mRecyclerView ;
    private TQCropSetsAdapt mTQCropSetsAdapt;
    private ArrayList<TQAtachModel> mAtachModels = new ArrayList<>();

    static public String PUBLISH_INFO = "PUBLISH_INFO";

    static public void show(Activity pActivity){
        Intent lIntent = new Intent(pActivity, TQCropPictureActivity.class);
        pActivity.startActivity(lIntent);
    }
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStatusBar();

        setContentView(R.layout.activity_fragment_layout);
        mHeader5View = findViewById(R.id.title);
        mHeader5View.getTitleView().setText("截取");
        mHeader5View.getBackIcon().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TQCropPictureActivity.this.finish();
            }
        });

        mRecyclerView = findViewById(R.id.content);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        if(mTQCropSetsAdapt == null){
            mTQCropSetsAdapt = new TQCropSetsAdapt(this);
            mTQCropSetsAdapt.setCropListener(mICropListener);
        }
        mRecyclerView.setAdapter(mTQCropSetsAdapt);
        mRecyclerView.setNestedScrollingEnabled(false);
        mRecyclerView.setBackgroundColor(Color.parseColor("#F6F7F8"));

        findViewById(R.id.next).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                gotoNext();
            }
        });
        findViewById(R.id.next).setVisibility(View.VISIBLE);

        if(TQPublishType.getSharePublishItem() instanceof TQNewPingJiangPublish) {
            TQNewPingJiangPublish publish = (TQNewPingJiangPublish) TQPublishType.getSharePublishItem();
            if (publish.getAtachModels().size() == 0) {
                gotoChoicepdf();
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if(resultCode != RESULT_OK) return;

        if(requestCode == 0x11){
            //
            String pdf = data.getStringExtra(TQPdfReaderActivity.RESULT_KEY);
            gotoCrop(pdf);
        }else if(requestCode == 0x12){
            ArrayList<String> files = data.getStringArrayListExtra(TQPdfReaderActivity.RESULT_KEY);

            TQLoadingHelper.build(this).setCancelable(false).show();
            uploadPics(files, 0);
        }

    }

    @Override
    protected void onStart() {
        super.onStart();
        bindData();
    }

    private void bindData(){
        if(TQPublishType.getSharePublishItem() instanceof TQNewPingJiangPublish){
            TQNewPingJiangPublish publish = (TQNewPingJiangPublish)TQPublishType.getSharePublishItem();
            mTQCropSetsAdapt.replace(publish.getAtachModels());
        }
    }

    private TQCropSetsAdapt.ICropListener mICropListener = new TQCropSetsAdapt.ICropListener() {
        @Override
        public void onChoice() {
            Log.d(TAG, "onChoice: ");
            gotoChoicepdf();
        }

        @Override
        public void onDelete(final TQAtachModel file) {
            if(file == null) return;

            AlertDialogHelper.show(TQCropPictureActivity.this, "确定删除?", new AlertDialogHelper.ISumbimtListener() {
                @Override
                public void ok() {
                    if(TQPublishType.getSharePublishItem() instanceof TQNewPingJiangPublish) {
                        final TQNewPingJiangPublish publish = (TQNewPingJiangPublish) TQPublishType.getSharePublishItem();

                        TQLoadingHelper.build(TQCropPictureActivity.this).setCancelable(false).show();
                        TQNetInterface.delMaterialAttrach(file.getId(), new INetCallback() {
                            @Override
                            public void result(TQNetResult pNetResult) {
                                if(!pNetResult.isSuccess()){
                                    TQLoadingHelper.setError(pNetResult.getErrMsg());
                                    return;
                                }
                                try {
                                    publish.delAttach(file);
                                    mTQCropSetsAdapt.replace(publish.getAtachModels());
                                }finally {
                                    TQLoadingHelper.dimiss();
                                }
                            }
                        });
                    }
                }
            });

        }

        @Override
        public void onShow(TQAtachModel file) {
            String url = TQPictureUpload.downloadPath(file.getCover());
            ArrayList<String> pic = new ArrayList<>();
            pic.add(url);

            DetailPicsActivity.jumpToThis(TQCropPictureActivity.this, pic, 0);
        }
    };

    private void gotoCrop(String fileId){
        TQPdfReaderActivity.showCrop(this, fileId,0x12);
    }

    private void gotoNext(){
        TQPublishType.showPublishNextStep(this);
        this.finish();
    }

    private void gotoChoicepdf(){
        TQDirectoryActivity.showSelect(this, 0x11, TQSystemDefine.FILE_TYPE_PDF);
    }

    private void uploadPics(final ArrayList<String> file, final int index){
        if(index >= file.size()){
            TQLoadingHelper.dimiss();
            addAttach();
            return;
        }

        TQLoadingHelper.setText(String.format("正在上传%d/%d", index, file.size()));
        TQPictureUpload.uploadPicture(file.get(index), new INetCallback() {
            @Override
            public void result(TQNetResult pNetResult) {
                if(!pNetResult.isSuccess()){
//                    AlertDialogHelper.show(TQCropPictureActivity.this, pNetResult.getErrMsg());
                    TQLoadingHelper.setError(pNetResult.getErrMsg());
                    return;
                }

                if(pNetResult.getData() == null) return;
                String id = pNetResult.getData().optString("fid");

                TQAtachModel lAtachModel = new TQAtachModel();
                lAtachModel.setCover(id);
                mAtachModels.add(lAtachModel);

                int i = index + 1;
                uploadPics(file, i);
            }
        });
    }

    private void addAttach(){

        if(mAtachModels.size() == 0){
            return;
        }

        ArrayList<HashMap<String, String>> allAttach = new ArrayList<>();
        for (TQAtachModel attach:
                mAtachModels) {
            allAttach.add(attach.getHashInfo());
        }

        final TQNewPingJiangPublish lTQNewPingJiangPublish = (TQNewPingJiangPublish) TQPublishType.getSharePublishItem();
        TQLoadingHelper.build(this).setCancelable(false).show();
        TQNetInterface.attachFile2Material(lTQNewPingJiangPublish.getSeq_id(), allAttach, new INetCallback() {
            @Override
            public void result(TQNetResult pNetResult) {
                if(!pNetResult.isSuccess()){
                    TQLoadingHelper.setError(pNetResult.getErrMsg());
                    return;
                }

                try{
                    if(pNetResult.getData() == null) return;

                    JSONObject save = pNetResult.getData().optJSONObject("saved");
                    if(save == null) return;

                    JSONArray attachs = save.optJSONArray("attachment");
                    if(attachs == null)return;
                    for (int i = 0; i < attachs.length(); i++){
                        JSONObject lObject = attachs.optJSONObject(i);
                        if(lObject == null) continue;

                        TQAtachModel lAtachModel = new TQAtachModel();
                        lAtachModel.fromJson(lObject);

                        lTQNewPingJiangPublish.appendAttach(lAtachModel);
                    }

                    mTQCropSetsAdapt.replace(lTQNewPingJiangPublish.getAtachModels());
                    bindData();
                }finally {
                    mAtachModels.clear();
                    TQLoadingHelper.dimiss();
                }
            }
        });
    }
}
